package com.jspgou.cms.action.admin.main;

import static com.jspgou.common.page.SimplePage.cpn;

import java.io.UnsupportedEncodingException;
import java.util.Date;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jspgou.common.page.Pagination;
import com.jspgou.common.web.CookieUtils;
import com.jspgou.core.entity.EmailSender;
import com.jspgou.core.entity.MessageTemplate;
import com.jspgou.core.entity.Website;
import com.jspgou.core.manager.LogMng;
import com.jspgou.core.web.SiteUtils;
import com.jspgou.core.web.WebErrors;
import com.jspgou.cms.entity.Noctice;
import com.jspgou.cms.entity.Product;
import com.jspgou.cms.manager.NocticeMng;
import com.jspgou.cms.manager.ProductMng;

@Controller
public class NocticeAct {
	private static final Logger log = LoggerFactory.getLogger(NocticeAct.class);

	@RequestMapping("/noctice/v_list.do")
	public String list(Integer pageNo, HttpServletRequest request,
			ModelMap model) {
		Pagination pagination = manager.getPage(cpn(pageNo),
				CookieUtils.getPageSize(request));
		model.addAttribute("pagination", pagination);
		model.addAttribute("pageNo", pageNo);
		return "noctice/list";
	}

	@RequestMapping("/noctice/v_add.do")
	public String add(ModelMap model) {
		return "noctice/add";
	}

	@RequestMapping("/noctice/v_edit.do")
	public String edit(Integer id, Integer pageNo, HttpServletRequest request,
			ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		model.addAttribute("noctice", manager.findById(id));
		model.addAttribute("pageNo", pageNo);
		return "noctice/edit";
	}

	@RequestMapping("/noctice/o_save.do")
	public String save(Noctice bean, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateSave(bean, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		bean = manager.save(bean);
		log.info("save Noctice id={}", bean.getId());
		logMng.operating(request, "发送到货通知", "id="+bean.getUser().getId()+" ;name"+bean.getUser().getUsername());
		return "redirect:v_list.do";
	}

	@RequestMapping("/noctice/o_update.do")
	public String update(Noctice bean, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateUpdate(bean.getId(), request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		bean = manager.update(bean);
		log.info("update Noctice id={}.", bean.getId());
		logMng.operating(request, "修改到货通知", "id="+bean.getUser().getId()+" ;name"+bean.getUser().getUsername());
		return list(pageNo, request, model);
	}

	private WebErrors validateUpdate(Integer id, HttpServletRequest request) {

		return null;
	}

	@RequestMapping("/noctice/o_delete.do")
	public String delete(Integer[] ids, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateDelete(ids, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		Noctice[] beans = manager.deleteByIds(ids);
		for (Noctice bean : beans) {
			log.info("delete Noctice id={}", bean.getId());
			logMng.operating(request, "删除到货通知", "id="+bean.getUser().getId()+" ;name="+bean.getUser().getId());
		}
		return list(pageNo, request, model);
	}

	/**
	 * 发送邮件
	 * 
	 * @param bean
	 * @param request
	 * @return
	 * @return
	 */
	@RequestMapping("/noctice/o_senderEmail.do")
	public String senderEmail(Integer[] ids, HttpServletRequest request)
			throws MailException {
		Website web = SiteUtils.getWeb(request);
		final EmailSender email = web.getEmailSender();
		for (Integer i = 0; i < ids.length; i++) {
			Noctice noctice = manager.findById(ids[i]);
			final String to = noctice.getUser().getEmail();
			noctice.setNocticeTime(new Date());
			noctice = manager.save(noctice);
			JavaMailSenderImpl sender = new JavaMailSenderImpl(); // JavaMailSender用来发送邮件的类
			sender.setHost(email.getHost());// 服务器邮箱地址
			sender.setUsername(email.getUsername());// 用户名
			sender.setPassword(email.getPassword());// 密码
			sender.send(new MimeMessagePreparator() { // 邮件模板，支持文本、附件、html、图片等
				public void prepare(MimeMessage mimemessage)
						throws MessagingException, UnsupportedEncodingException {
					MimeMessageHelper msg = new MimeMessageHelper(mimemessage,
							false, email.getEncoding());// 创建MimeMessageHelper对象，处理MimeMessage的辅助类
					// 使用辅助类MimeMessage设定参数
					msg.setSubject("到货通知");// 邮件设置邮件主题
					msg.setTo(to);// 设置接收方的email地址
					msg.setFrom(email.getUsername(), email.getPersonal());// 邮件的发件人
					String text = "尊敬的用户：JSPGOU提醒您!您的货物已到货！"; // 邮件正文
					msg.setText(text, true);// 将发送的内容赋值给MimeMessageHelper,后面的true表示内容解析成html

				}
				
			});
			logMng.operating(request, "发送到货通知", "id="+noctice.getUser().getId()+" ;name="+noctice.getUser().getUsername()); 
		}
		return "redirect:v_list.do";

	}

	private WebErrors validateSave(Noctice bean, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		Website web = SiteUtils.getWeb(request);
		// bean.setWebsite(web);
		return errors;
	}

	private WebErrors validateEdit(Integer id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		Website web = SiteUtils.getWeb(request);
		if (vldExist(id, web.getId(), errors)) {
			return errors;
		}
		return errors;
	}

	private WebErrors validateUpdate1(Integer id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		Website web = SiteUtils.getWeb(request);
		if (vldExist(id, web.getId(), errors)) {
			return errors;
		}
		return errors;
	}

	private WebErrors validateDelete(Integer[] ids, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		Website web = SiteUtils.getWeb(request);
		errors.ifEmpty(ids, "ids");
		for (Integer id : ids) {
			vldExist(id, web.getId(), errors);
		}
		return errors;
	}

	private boolean vldExist(Integer id, Long webId, WebErrors errors) {
		if (errors.ifNull(id, "id")) {
			return true;
		}
		Noctice entity = manager.findById(id);
		if (errors.ifNotExist(entity, Noctice.class, id)) {
			return true;
		}
		// if (!entity.getWebsite().getId().equals(webId)) {
		// errors.notInWeb(Noctice.class, id);
		// return true;
		// }
		return false;
	}

	@Autowired
	private NocticeMng manager;
	@Autowired
	private ProductMng productMng;
	@Autowired
	private LogMng logMng;

}